<template>
    <div>
        <el-table :data="computedTableData" style="width: 100%">
            <el-table-column label="姓名" width="180">
                <template #header>
                    <el-input v-model="search" size="small" placeholder="请输入名字" />
                </template>
                <template #default="scope">
                    {{ scope.row.studentname }}
                </template>
            </el-table-column>
            <el-table-column label="班级" :filters="computedClass" :filter-method="filterClass" filter-placement="bottom-end">
                <template #default="scope">
                    {{ scope.row.class.title }}
                </template>
            </el-table-column>
            <el-table-column label="综合评分">
                <template #default="scope">
                    <el-rate :model-value="getRate(scope.row)" :colors="colors" disabled allow-half />
                </template>
            </el-table-column>
            <el-table-column label="评分进度" width="180">
                <template #default="scope">
                    <el-progress :percentage="getProgress(scope.row)" />
                </template>

            </el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <div style="display: flex; align-items: center;height: 55px;">
                        <el-badge :value="getBadge(scope.row)" class="item" :hidden="getBadge(scope.row) <= 0">
                            <el-button type="primary" round @click="handleRate(scope.row)">评分</el-button>
                        </el-badge>

                    </div>
                </template>
            </el-table-column>
        </el-table>

        <el-drawer v-model="outerDrawer" direction="rtl" :size="size">
            <template #header>
                <h2>评分</h2>
            </template>
            <div>
                <el-button type="primary" :icon="PieChart" round @click="handlePie"></el-button>
                <el-divider />
                <el-alert type="info" show-icon>
                    请为<b style="font-size: 18px;">{{ currentItem.studentname }}</b>评分
                </el-alert>
                <el-divider />

                <div v-for="item in tagsData" :key="item._id">
                    <div class="rate-item">
                        <div>{{ item.title }}</div>
                        <el-rate :model-value="getItemRate(item.title)" :colors="colors" allow-half
                            @change="handleRateEven($event, item.title)" tabindex="-1" />
                    </div>
                    <el-divider />
                </div>
            </div>
            <el-drawer v-model="innerDrawer" size="50%" title="可视化分析" :append-to-body="true" :before-close="handleClose">
                <StudentChart v-if="innerDrawer" :data="{tableData,currentItem,tagsData}"></StudentChart>
            </el-drawer>
        </el-drawer>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import axios from 'axios'
import { PieChart, } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import StudentChart from '../../components/student-manage/studentChart.vue'
const colors = ref(['#99A9BF', '#F7BA2A', '#FF9900']) // same as { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }

const tableData = ref([])
const classList = ref([])
const tagsData = ref([])
const search = ref('')
const outerDrawer = ref(false)
const size = ref('30%')
onMounted(async () => {
    getList()
    getClass()
    getTags()
})

// 记录当前点击的item
const currentItem = ref({})


const getList = async () => {
    let res = await axios.get('/adminapi/students')
    tableData.value = res.data
}
const getClass = async () => {
    let res = await axios.get('/adminapi/classes')
    classList.value = res.data
}
const getTags = async () => {
    let res = await axios.get('/adminapi/tags')
    tagsData.value = res.data

}



const computedTableData = computed(() => tableData.value.filter(
    item => item.studentname.toLowerCase().includes(search.value.toLowerCase()))
)

// class筛选
const computedClass = computed(() => {
    return classList.value.map(item => ({
        text: item.title,
        value: item._id
    }))
})
// 筛选
const filterClass = (value, item) => {
    // console.log(value,item)
    return value === item.class._id
}

// 评分
const handleRate = (item) => {
    outerDrawer.value = true
    currentItem.value = item
}

// 每一个评分项的
const handleRateEven = async (value, item) => {
    // console.log(value)
    // console.log(item)
    await axios.put(`/adminapi/students/${currentItem.value._id}`, {
        key: item,
        value: value
    }).then(() => {
        ElMessage({
            showClose: true,
            message: `${currentItem.value.studentname}的${item}评分已更新`,
            type: 'success',
        })
    })

    await getList()
}

const getItemRate = (title) => {
    // return currentItem.value.score[title]  // 直接返回的话是旧的评分，不会实时更新
    return tableData.value.filter(item => item._id === currentItem.value._id)[0].score[title]
}

// 获取badge的值
const getBadge = ({ score }) => {
    let keys = Object.keys(score)
    return tagsData.value.length - keys.length
}

// 获取进度条的值
const getProgress = ({ score }) => {
    if (tagsData.value.length == 0) return 0
    let keys = Object.keys(score)
    let num = Math.round(keys.length / tagsData.value.length * 100)
    if (num >= 100) { num = 100 } else if (num <= 0) num = 0   // 防止之前的评分项被删除后，进度条出现负数
    return num
}

// 获取综合评分
const getRate = ({ score }) => {
    let keys = Object.keys(score)
    let sum = 0
    keys.forEach(item => {
        sum += score[item]
    })
    return sum / keys.length
}

// pie
const innerDrawer = ref(false)
const handlePie = () => {
    innerDrawer.value = true
    // 改变外部抽屉的大小
    size.value = '70%'
}

const handleClose = () => {
    innerDrawer.value = false
    size.value = '30%'
}

</script>


<style scoped  lang="scss">
.rate-item {
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
</style>